﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using TcpSocket;
using UnityEngine;
using UnityEngine.UI;

public class GameManager : MonoBehaviour
{
    public static GameManager Instence = null;

    public Dropdown dropdown;
    public ScrollRect scrollRect;
    public Text messageText;
    public InputField fieldText;
    public Button sendBtn;

    public string textMessage = null;

    private void Awake()
    {
        Instence = this;
    }
    private void Start()
    {
        messageText.text = "";
        sendBtn.onClick.AddListener(OnSendMessage);
    }

    private void Update()
    {
        if (textMessage != null)
        {
            SetText(textMessage);
            textMessage = null;
        }
    }

    void OnSendMessage()
    {
        try
        {
            string str = fieldText.text;
            if (string.IsNullOrEmpty(str)) return;
            int index = dropdown.value;
            string n = dropdown.options[index].text;
            if (n.Length > 0)
            {
                bool state = SocketServerManager.OnSendToClient(n, str); if (state)
                {
                    _setText(str);
                }
            }
            else
            {
                SocketServerManager.OnSendAllMsg(str);
                _setText(str);
            }
        }
        catch (Exception)
        {

        }

    }

    void _setText(string str)
    {
            fieldText.text = "";
            messageText.text += "我=>: " + str + "\n";
            scrollRect.verticalScrollbar.value = 0;
    }

    public void SetText(string msg)
    {
        messageText.text +=  msg + "\n";
        scrollRect.verticalScrollbar.value = 0;
    }

    public void AddDropdownOptionData(string idStr)
    {
        Dropdown.OptionData option = new Dropdown.OptionData();
        option.text = idStr;
        dropdown.options.Add(option);
    }

    public void RemoveDropdownOptionData(string idStr)
    {
        for (int i = dropdown.options.Count - 1; i >= 0; i--)
        {
            if (dropdown.options[i].text == idStr)
            {
                dropdown.options.RemoveAt(i);
            }
        }
    }
}
